package org.timeismoney.payment.web.action.stu;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.timeismoney.payment.common.Constants;
import org.timeismoney.payment.common.Md5Util;
import org.timeismoney.payment.common.PageBean;
import org.timeismoney.payment.exception.BizException;
import org.timeismoney.payment.model.Student;
import org.timeismoney.payment.service.StudentService;
import org.timeismoney.payment.web.WebUtils;
import org.timeismoney.payment.web.action.BaseAction;
import org.timeismoney.payment.web.form.StudentForm;

public class StuAction extends BaseAction {
	private static Logger	log	= Logger.getLogger(StuAction.class);
	private StudentService	service;

	public void setService(StudentService service) {
		this.service = service;
	}

	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			Student student = (Student) request.getSession().getAttribute(
					Constants.USER_IN_SESSION);
			List<Student> stuList = new ArrayList<Student>();
			if (student != null)
				stuList.add(student);
			PageBean<Student> pageBean = new PageBean<Student>(1,
					stuList.size(), 10, stuList);
			renderJson(response, WebUtils.generateJSONByPageBean(pageBean));
		} catch (Exception e) {
			log.error(e.getMessage());
			renderJson(
					response,
					WebUtils.generateErrorJSON(TEXT_ERROR_MSG_QUERY + " "
							+ e.getMessage()));
		}
		return null;
	}

	public ActionForward pwd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			StudentForm studentForm = (StudentForm) form;
			Student stu = service.get(studentForm.getStuNo());
			if (!stu.getPwd().equals(Md5Util.MD5(studentForm.getOrigPwd().trim()))) {
				throw new BizException("原始密码错误");
			}
			stu.setPwd(Md5Util.MD5(studentForm.getPwd()));
			service.update(stu);
		} catch (Exception e) {
			log.error(e.getMessage());
			renderJson(
					response,
					WebUtils.generateErrorJSON(TEXT_ERROR_MSG_EDIT + " "
							+ e.getMessage()));
		}
		return null;
	}
}
